package org.nmgyjt.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.nmgyjt.springboot.beans.admin.CsBusinessUserAuthParamDTO;
import org.nmgyjt.springboot.beans.dto.*;
import org.nmgyjt.springboot.beans.vo.CsBusineesUserCodeVo;
import org.nmgyjt.springboot.beans.vo.CsBusinessUserAuthListVo;
import org.nmgyjt.springboot.beans.vo.CsBusinessUserListVo;
import org.nmgyjt.springboot.entity.ApiCodeEnum;
import org.nmgyjt.springboot.entity.ApiRes;
import org.nmgyjt.springboot.entity.admin.*;
import org.nmgyjt.springboot.entity.exception.BizException;
import org.nmgyjt.springboot.service.*;
import org.nmgyjt.springboot.utils.IDAASUserUtils;
import org.nmgyjt.springboot.utils.JsonDataSecurity;
import org.nmgyjt.springboot.utils.ServerIpUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
@Transactional
public class BusinessAuthServiceImpl implements IBusinessAuthService {

    @Autowired
    private ICsBusinessService csBusinessService;

//    @Autowired
//    private ICsBusinessUserCodeService csBusinessUserCodeService;

    @Autowired
    private ICsBusinessUserAuthService csBusinessUserAuthService;

    @Autowired
    private ICsBusinessUserService csBusinessUserService;

    @Autowired
    private ICsBusinessAuthCodeService csBusinessAuthCodeService;

    @Override
    public void addAuthUser(BusAuthUserAddDto bean) throws Exception {
        List<BusAuthUserCodeDto> authUserDtoList = bean.getAuthUserDtos();
        Date newDate = new Date();
        Map<String, AuthUserDTO> busMap = new HashMap<>();

        for (BusAuthUserCodeDto busAuthUserCodeDto : authUserDtoList) {
            String businessId = busAuthUserCodeDto.getBusinessId();

            String buid = "";
            if (businessId.contains("=")) {
                buid = businessId.split("=")[0];
            } else {
                buid = businessId;
            }
            AuthUserDTO authUserDTO = busMap.get(buid);

            CsBusiness business = csBusinessService.findByBusinessId(businessId);
            CsBusiness businessP = csBusinessService.findByBusinessId(business.getParentId());

            if (null == authUserDTO) {

                authUserDTO = new AuthUserDTO();
                List<DbAuthUserDto> dbAuthUserDtoList = new ArrayList<>();
                //找到角色对应的秘钥

                DbAuthUserDto dbAuthUserDto = new DbAuthUserDto();
                dbAuthUserDto.setBusinessId(businessId);
                dbAuthUserDto.setBusinessName(business.getName());
                dbAuthUserDto.setParentBusinessId(businessP.getBusinessId());
                dbAuthUserDto.setParentBusinessName(businessP.getName());
                dbAuthUserDto.setPhone(bean.getPhone());
                dbAuthUserDto.setUserName(bean.getUserName());
                dbAuthUserDto.setAuthPhone(bean.getAuthPhone());
                dbAuthUserDto.setAuthUserName(bean.getAuthUserName());
                dbAuthUserDto.setAreaCode(bean.getAreaCode());
                dbAuthUserDto.setAreaName(bean.getAreaName());
                dbAuthUserDto.setOrgId(bean.getOrgId());
                dbAuthUserDto.setOrgName(bean.getOrgName());
                dbAuthUserDto.setDeptId(bean.getDeptId());
                dbAuthUserDto.setDeptName(bean.getDeptName());
                dbAuthUserDto.setIp(bean.getIp());
                dbAuthUserDto.setCreatedTime(newDate);

                SyncAuthUserDto syncAuthUserDto = new SyncAuthUserDto();
                syncAuthUserDto.setBusinessIds(businessId);
                syncAuthUserDto.setPhone(bean.getPhone());
                syncAuthUserDto.setUserName(bean.getUserName());
                syncAuthUserDto.setAuthPhone(bean.getAuthPhone());
                syncAuthUserDto.setAuthUserName(bean.getAuthUserName());
                syncAuthUserDto.setIp(bean.getIp());
                syncAuthUserDto.setSalt(business.getSalt());
                syncAuthUserDto.setAuthUrl(business.getAuthUrl());
                syncAuthUserDto.setSystemCode(business.getSystemCode());

                List<CsBusineesUserCodeVo> authUserCodeDtoList = busAuthUserCodeDto.getAuthUserCodeDtos();
                for (CsBusineesUserCodeVo cbycv : authUserCodeDtoList) {
                    if (cbycv.getIschecked()) {

                        dbAuthUserDto.setAuthCode(cbycv.getAuthCode());
                        dbAuthUserDto.setAuthName(cbycv.getAuthName());
                        dbAuthUserDtoList.add(dbAuthUserDto);

                        syncAuthUserDto.setAuthCode(cbycv.getAuthCode());

                    }
                }


                authUserDTO.setDbAuthUserDtoList(dbAuthUserDtoList);
                authUserDTO.setSyncAuthUserDto(syncAuthUserDto);
                busMap.put(buid, authUserDTO);
            } else {

                List<DbAuthUserDto> dbAuthUserDtoList = authUserDTO.getDbAuthUserDtoList();
                SyncAuthUserDto syncAuthUserDto = authUserDTO.getSyncAuthUserDto();
                String businessIds = syncAuthUserDto.getBusinessIds();
                syncAuthUserDto.setBusinessIds(businessIds + "," + businessId);

                List<CsBusineesUserCodeVo> authUserCodeDtoList = busAuthUserCodeDto.getAuthUserCodeDtos();
                DbAuthUserDto dbAuthUserDto = new DbAuthUserDto();
                dbAuthUserDto.setBusinessId(businessId);
                dbAuthUserDto.setBusinessName(business.getName());
                dbAuthUserDto.setParentBusinessId(businessP.getBusinessId());
                dbAuthUserDto.setParentBusinessName(businessP.getName());
                dbAuthUserDto.setPhone(bean.getPhone());
                dbAuthUserDto.setUserName(bean.getUserName());
                dbAuthUserDto.setAuthPhone(bean.getAuthPhone());
                dbAuthUserDto.setAuthUserName(bean.getAuthUserName());
                dbAuthUserDto.setAreaCode(bean.getAreaCode());
                dbAuthUserDto.setAreaName(bean.getAreaName());
                dbAuthUserDto.setOrgId(bean.getOrgId());
                dbAuthUserDto.setOrgName(bean.getOrgName());
                dbAuthUserDto.setDeptId(bean.getDeptId());
                dbAuthUserDto.setDeptName(bean.getDeptName());
                dbAuthUserDto.setIp(bean.getIp());
                dbAuthUserDto.setCreatedTime(newDate);

                for (CsBusineesUserCodeVo cbycv : authUserCodeDtoList) {
                    if (cbycv.getIschecked()) {

                        dbAuthUserDto.setAuthCode(cbycv.getAuthCode());
                        dbAuthUserDto.setAuthName(cbycv.getAuthName());
                        dbAuthUserDtoList.add(dbAuthUserDto);

                        String authCode = syncAuthUserDto.getAuthCode();
                        if (StrUtil.isEmpty(authCode)) {
                            syncAuthUserDto.setAuthCode(cbycv.getAuthCode());
                        } else {
                            syncAuthUserDto.setAuthCode(authCode + "," + cbycv.getAuthCode());
                        }
                    }
                }
            }
        }

        //---- authUserDtoList end

        Set<String> setData = busMap.keySet();

        for (String businessId : setData) {
            log.info("businessId :{} ", businessId);

            AuthUserDTO authUserDTO = busMap.get(businessId);
            List<DbAuthUserDto> dbAuthUserDtoList = authUserDTO.getDbAuthUserDtoList();
            SyncAuthUserDto syncAuthUserDto = authUserDTO.getSyncAuthUserDto();

            String authCode = syncAuthUserDto.getAuthCode();
            String businessIds = syncAuthUserDto.getBusinessIds();
            if (StrUtil.isNotEmpty(authCode)) {

                boolean tb = false;


                //查询code是否存在
                String[] authCodeStr = authCode.split(",");
                String[] businessIdsStr = businessIds.split(",");
                for (int i = 0; i < authCodeStr.length; i++) {
                    String ac = authCodeStr[i];
                    LambdaQueryWrapper qw = new LambdaQueryWrapper<CsBusinessUserAuth>()
                            .eq(CsBusinessUserAuth::getPhone, bean.getPhone())
                            .eq(CsBusinessUserAuth::getBusinessId, businessIdsStr[i])
                            .eq(CsBusinessUserAuth::getAuthCode, ac);
                    int count = csBusinessUserAuthService.count(qw);
                    if (count <= 0) {
                        tb = true;
                    }
                }

                //特殊处理
                if (authCode.contains(",")) {
                    LambdaQueryWrapper qw = new LambdaQueryWrapper<CsBusinessUserAuth>()
                            .eq(CsBusinessUserAuth::getPhone, bean.getPhone())
                            .like(CsBusinessUserAuth::getBusinessId, businessId);
                    int count = csBusinessUserAuthService.count(qw);
                    if (authCodeStr.length < count) {
                        tb = true;
                    }
                }

                if (tb) {
                    try {

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("phone", syncAuthUserDto.getPhone());
                        jsonObject.put("userName", syncAuthUserDto.getUserName());
                        jsonObject.put("authPhone", syncAuthUserDto.getAuthPhone());
                        jsonObject.put("authUserName", syncAuthUserDto.getAuthUserName());
                        jsonObject.put("ip", syncAuthUserDto.getIp());
                        jsonObject.put("authCode", syncAuthUserDto.getAuthCode());
                        String sign = JsonDataSecurity.encryptJsonData(jsonObject, syncAuthUserDto.getSalt());
                        jsonObject.put("sign", sign);
                        log.info("syncUserAuthEdit-jsonObject:{} :{}", businessIds, jsonObject.toString());

                        if (null != syncAuthUserDto.getSystemCode() ){
                            ApiRes apiRes = addHierarchyConfirm(syncAuthUserDto.getPhone(), syncAuthUserDto.getSystemCode());
                            if (ApiCodeEnum.SUCCESS.getCode() != apiRes.getCode()) {
                                log.info("syncUserAuthEdit-erro-id:{}", businessId);
                            }
                        }else {
                            log.info("businessId-isSystemCode-null:{}",businessId);
                        }
                        int codeC =ApiCodeEnum.SUCCESS.getCode() ;
                        if (null !=  syncAuthUserDto.getAuthUrl()){
                            codeC = syncUserAuthEdit(jsonObject, syncAuthUserDto.getAuthUrl());
                        }
                        if (ApiCodeEnum.SUCCESS.getCode() != codeC) {
                            log.info("syncUserAuthEdit-erro-id:{}", businessId);
                        } else {

                            if (authCode.contains(",")) {
                                for (int i = 1; i < 5; i++) {
                                    csBusinessUserAuthService.remove(new LambdaQueryWrapper<CsBusinessUserAuth>()
                                            .eq(CsBusinessUserAuth::getPhone, bean.getPhone())
                                            .eq(CsBusinessUserAuth::getBusinessId, businessId + "=" + i));
//                                    csBusinessUserCodeService.remove(new LambdaQueryWrapper<CsBusinessUserCode>()
//                                            .eq(CsBusinessUserCode::getBusinessId, businessId + "=" + i)
//                                            .eq(CsBusinessUserCode::getPhone, bean.getPhone()));
                                    csBusinessUserService.remove(new LambdaQueryWrapper<CsBusinessUser>()
                                            .eq(CsBusinessUser::getPhone, bean.getPhone())
                                            .eq(CsBusinessUser::getBusinessId, businessId + "=" + i));
                                }
                            }

                            for (DbAuthUserDto dbAuthUserDto : dbAuthUserDtoList) {

                                CsBusinessUserAuth businessUserAuth = new CsBusinessUserAuth();
                                BeanUtils.copyProperties(dbAuthUserDto, businessUserAuth);
                                businessUserAuth.setBusinessId(dbAuthUserDto.getBusinessId());
                                businessUserAuth.setBusinessName(dbAuthUserDto.getBusinessName());
                                businessUserAuth.setParentBusinessId(dbAuthUserDto.getParentBusinessId());
                                businessUserAuth.setParentBusinessName(dbAuthUserDto.getParentBusinessName());

                                CsBusinessUserCode userCode = new CsBusinessUserCode();
                                BeanUtils.copyProperties(dbAuthUserDto, userCode);

                                CsBusinessUser csBusinessUser = new CsBusinessUser();
                                csBusinessUser.setBusinessId(dbAuthUserDto.getBusinessId());
                                csBusinessUser.setBusinessName(dbAuthUserDto.getBusinessName());
                                csBusinessUser.setParentBusinessId(dbAuthUserDto.getParentBusinessId());
                                csBusinessUser.setParentBusinessName(dbAuthUserDto.getParentBusinessName());
                                csBusinessUser.setCreatedTime(newDate);
                                csBusinessUser.setPhone(bean.getPhone());
                                csBusinessUser.setCreatedBy(bean.getAuthPhone());


                                csBusinessUserAuthService.remove(new LambdaQueryWrapper<CsBusinessUserAuth>()
                                        .eq(CsBusinessUserAuth::getPhone, bean.getPhone())
                                        .eq(CsBusinessUserAuth::getBusinessId, dbAuthUserDto.getBusinessId()));
                                csBusinessUserService.remove(new LambdaQueryWrapper<CsBusinessUser>()
                                        .eq(CsBusinessUser::getPhone, bean.getPhone())
                                        .eq(CsBusinessUser::getBusinessId, dbAuthUserDto.getBusinessId()));
//                                csBusinessUserCodeService.remove(new LambdaQueryWrapper<CsBusinessUserCode>()
//                                        .eq(CsBusinessUserCode::getBusinessId, dbAuthUserDto.getBusinessId())
//                                        .eq(CsBusinessUserCode::getPhone, bean.getPhone()));
                                csBusinessUserAuthService.save(businessUserAuth);
                                csBusinessUserService.save(csBusinessUser);
//                                csBusinessUserCodeService.save(userCode);
                            }
                        }

                    } catch (Exception e) {
                        log.info("addAuthUser-Exception-businessId:{} e:{}", businessId, e);
                    }
                } else {
                    log.info("not-b-businessId:{}", businessId);
                }

            } else {

                boolean tb = false;

                String[] businessIdsStr = businessIds.split(",");
                for (int i = 0; i < businessIdsStr.length; i++) {
                    String bi = businessIdsStr[i];
                    LambdaQueryWrapper qw = new LambdaQueryWrapper<CsBusinessUserAuth>()
                            .eq(CsBusinessUserAuth::getPhone, bean.getPhone())
                            .eq(CsBusinessUserAuth::getBusinessId, bi);
                    int count = csBusinessUserAuthService.count(qw);
                    if (count > 0) {
                        tb = true;
                    }
                }


                if (tb) {
                    //要查询人员的权限是否变动，
                    try {
                        //删除
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("phone", bean.getPhone());
                        jsonObject.put("userName", bean.getUserName());
                        jsonObject.put("authPhone", bean.getAuthPhone());
                        jsonObject.put("authUserName", bean.getAuthUserName());
                        jsonObject.put("ip", bean.getIp());
                        String sign = JsonDataSecurity.encryptJsonData(jsonObject, syncAuthUserDto.getSalt());
                        jsonObject.put("sign", sign);
                        log.info("syncDelUserAuth-jsonObject:{} :{} ", businessIds, jsonObject.toString());
                        int codeC = ApiCodeEnum.SUCCESS.getCode();
                        if (null != syncAuthUserDto.getAuthUrl()) {
                            codeC = syncDelUserAuth(jsonObject, syncAuthUserDto.getAuthUrl());
                        }

                        if (ApiCodeEnum.SUCCESS.getCode() == codeC) {

                            for (int i = 0; i < businessIdsStr.length; i++) {
                                String bi = businessIdsStr[i];
                                csBusinessUserAuthService.remove(new LambdaQueryWrapper<CsBusinessUserAuth>()
                                        .eq(CsBusinessUserAuth::getPhone, bean.getPhone())
                                        .eq(CsBusinessUserAuth::getBusinessId, bi));

                                csBusinessUserService.remove(new LambdaQueryWrapper<CsBusinessUser>()
                                        .eq(CsBusinessUser::getPhone, bean.getPhone())
                                        .eq(CsBusinessUser::getBusinessId, bi));

//                                    csBusinessUserCodeService.remove(new LambdaQueryWrapper<CsBusinessUserCode>()
//                                            .eq(CsBusinessUserCode::getBusinessId, bi)
//                                            .eq(CsBusinessUserCode::getPhone, bean.getPhone()));
                            }


                        } else {
                            log.info("syncDelUserAuth-erro-id:{}", businessId);
                        }
                    } catch (Exception e) {
                        log.info("syncDelUserAuth-Exception-businessId:{} e:{}", businessId, e);
                    }

                } else {
                    log.info("syncDelUserAuth-not-id:{}", businessId);
                }



            }

        }
        ;


    }

    @Override
    public List<CsBusinessUserListVo> getBuAuthCodeList(UserAuthCodeParamDto dto) {

        List<CsBusinessUserListVo> list = csBusinessUserService.userByBusiness(dto.getAuthPhone());
        if (CollUtil.isNotEmpty(list)) {
            for (CsBusinessUserListVo csBusinessUser : list) {

//                QueryWrapper<CsBusinessUserCode> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("business_id", csBusinessUser.getBusinessId());
//                queryWrapper.eq("phone", dto.getAuthPhone());


                QueryWrapper<CsBusinessAuthCode> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("business_id", csBusinessUser.getBusinessId());
                queryWrapper.eq("parent_business_id", csBusinessUser.getParentId());


                List<CsBusinessAuthCode> codeList =   csBusinessAuthCodeService.list(queryWrapper);
//                List<CsBusinessUserCode> csBusinessAuthCodes = csBusinessUserCodeService.list(queryWrapper);

                List<CsBusineesUserCodeVo> codeVos = new ArrayList<>();
                for (CsBusinessAuthCode cbac : codeList) {
                    CsBusineesUserCodeVo vo = new CsBusineesUserCodeVo();
                    vo.setAuthCode(cbac.getAuthCode());
                    vo.setAuthName(cbac.getAuthName());
                    vo.setIschecked(false);


                    QueryWrapper<CsBusinessUserAuth> authQueryWrapper = new QueryWrapper<>();
                    authQueryWrapper.eq("business_id", csBusinessUser.getBusinessId());
                    authQueryWrapper.eq("phone", dto.getPhone());
                    authQueryWrapper.eq("auth_code", cbac.getAuthCode());
                    List<CsBusinessUserAuth> code = csBusinessUserAuthService.list(authQueryWrapper);

                    if (CollUtil.isNotEmpty(code)) {
                        vo.setIschecked(true);
                    }
                    codeVos.add(vo);
                }
                csBusinessUser.setAuthUserCodeDtos(codeVos);
            }
        }
        return list;
    }

    @Override
    public List<CsBusiness> businessAllList() {
        return csBusinessService.businessAllList();
    }

    @Override
    public IPage<CsBusinessUserAuthListVo> listPage(CsBusinessUserAuthParamDTO bean) {
        IPage<CsBusinessUserAuthListVo> iPage = csBusinessUserAuthService.listPage(bean);
        List<CsBusinessUserAuthListVo> list = iPage.getRecords();
        for (CsBusinessUserAuthListVo vo : list) {
            String phone = vo.getPhone();
            if (null != phone){
                vo.setPhone(phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
            String authPhone = vo.getAuthPhone();
            if (null != authPhone){
                vo.setAuthPhone(authPhone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
        }
        return iPage;
    }

    public Integer syncUserAuthEdit(JSONObject json, String url) {
        // 添加请求头信息
        Map<String, String> heads = new HashMap<>();
        // 使用json发送请求，下面的是必须的
        heads.put("Content-Type", "application/json;charset=UTF-8");

        /**
         ** headerMap是添加的请求头，
         body是传入的参数，这里选择json，后端使用@RequestBody接收
         */

        log.info("syncUserAuthEdit-url:{} ", url + "/userAuthEdit");
        HttpResponse response = HttpRequest.post(url + "/userAuthEdit")
                .headerMap(heads, false)
                .body(json.toString())
                .timeout(5 * 60 * 1000)
                .execute();
        String result = response.body();
        log.info("syncUserAuthEdit-result:{} ", result);
        ApiRes wxResultDTO = JSONUtil.toBean(result, ApiRes.class);
        return wxResultDTO.getCode();
    }

    public Integer syncDelUserAuth(JSONObject json, String url) {
        // 添加请求头信息
        Map<String, String> heads = new HashMap<>();
        // 使用json发送请求，下面的是必须的
        heads.put("Content-Type", "application/json;charset=UTF-8");

        /**
         ** headerMap是添加的请求头，
         body是传入的参数，这里选择json，后端使用@RequestBody接收
         */
        log.info("syncDelUserAuth-url:{} ", url + "/delUserAuth");
        HttpResponse response = HttpRequest.post(url + "/delUserAuth")
                .headerMap(heads, false)
                .body(json.toString())
                .timeout(5 * 60 * 1000)
                .execute();
        String result = response.body();
        log.info("syncDelUserAuth-result:{}", result);
        ApiRes wxResultDTO = JSONUtil.toBean(result, ApiRes.class);
        return wxResultDTO.getCode();
    }

    @Override
    public void defaultBuAuth(BusAuthUserAddDto bean) {
        try {
            List<CsBusiness> businessList = csBusinessService.findByPoneOrCodeNot(bean.getAuthPhone());
            log.info("defaultBuAuth-phoneC:{}", bean.getAuthPhone());

            if (CollUtil.isNotEmpty(businessList)) {
                List<BusAuthUserCodeDto> authUserDtos = new ArrayList<>();
                for (CsBusiness csBusiness : businessList) {
                    String authCode = csBusiness.getAuthCode();
                    LambdaQueryWrapper<CsBusinessAuthCode> queryWrapper = new LambdaQueryWrapper<CsBusinessAuthCode>()
                            .eq(CsBusinessAuthCode::getAuthCode, authCode);
                    List<CsBusinessAuthCode> csBusinessAuthCodeList = csBusinessAuthCodeService.list(queryWrapper);
                    CsBusinessAuthCode csBusinessAuthCode = csBusinessAuthCodeList.get(0);

                    BusAuthUserCodeDto busAuthUserCodeDto = new BusAuthUserCodeDto();
                    busAuthUserCodeDto.setBusinessId(csBusiness.getBusinessId());
                    List<CsBusineesUserCodeVo> authUserCodeDtos = new ArrayList<>();
                    CsBusineesUserCodeVo csBusineesUserCodeVo = new CsBusineesUserCodeVo();
                    csBusineesUserCodeVo.setAuthCode(csBusinessAuthCode.getAuthCode());
                    csBusineesUserCodeVo.setAuthName(csBusinessAuthCode.getAuthName());
                    csBusineesUserCodeVo.setIschecked(true);

                    authUserCodeDtos.add(csBusineesUserCodeVo);
                    busAuthUserCodeDto.setAuthUserCodeDtos(authUserCodeDtos);
                    authUserDtos.add(busAuthUserCodeDto);
                }
                bean.setAuthUserDtos(authUserDtos);
                log.info("defaultBuAuth-authUserDtos:{}", JSONUtil.toJsonStr(bean));
                addAuthUser(bean);
            } else {
                log.info("defaultBuAuth-not-phoneC:{}", bean.getAuthPhone(), JSONUtil.toJsonStr(bean));
            }

        } catch (Exception e) {
            log.info("defaultBuAuth e:{}", e);
        }

    }

    /**
     * 成员单位授权
     *
     * @param cyBusAuthUserAddDto
     */
    @Override
    public void cydwsq(CyBusAuthUserAddDto cyBusAuthUserAddDto) {
        try {
            log.info("cydwsq: {}",JSONUtil.toJsonStr(cyBusAuthUserAddDto));

            Map<String, AuthUserDTO> busMap = new HashMap<>();

            List<CyBusAuthUserCodeDto> authUserDtos = cyBusAuthUserAddDto.getAuthUserDtos();
            Date newDate = new Date();

            for (CyBusAuthUserCodeDto authUserD : authUserDtos) {
                String businessId = authUserD.getBusinessId();

                String buid = "";
                if (businessId.contains("=")) {
                    buid = businessId.split("=")[0];
                } else {
                    buid = businessId;
                }
                AuthUserDTO authUserDTO = busMap.get(buid);

                CsBusiness business = csBusinessService.findByBusinessId(businessId);
                CsBusiness businessP = csBusinessService.findByBusinessId(business.getParentId());

                if (null == authUserDTO) {

                    authUserDTO = new AuthUserDTO();
                    List<DbAuthUserDto> dbAuthUserDtoList = new ArrayList<>();
                    //找到角色对应的秘钥

                    DbAuthUserDto dbAuthUserDto = new DbAuthUserDto();
                    dbAuthUserDto.setBusinessId(businessId);
                    dbAuthUserDto.setBusinessName(business.getName());
                    dbAuthUserDto.setParentBusinessId(businessP.getBusinessId());
                    dbAuthUserDto.setParentBusinessName(businessP.getName());
                    dbAuthUserDto.setPhone(cyBusAuthUserAddDto.getPhone());
                    dbAuthUserDto.setUserName(cyBusAuthUserAddDto.getUserName());
                    dbAuthUserDto.setAuthPhone(cyBusAuthUserAddDto.getAuthPhone());
                    dbAuthUserDto.setAuthUserName(cyBusAuthUserAddDto.getAuthUserName());
                    dbAuthUserDto.setAreaCode(cyBusAuthUserAddDto.getAreaCode());
                    dbAuthUserDto.setAreaName(cyBusAuthUserAddDto.getAreaName());
                    dbAuthUserDto.setOrgId(cyBusAuthUserAddDto.getOrgId());
                    dbAuthUserDto.setOrgName(cyBusAuthUserAddDto.getOrgName());
                    dbAuthUserDto.setDeptId(cyBusAuthUserAddDto.getDeptId());
                    dbAuthUserDto.setDeptName(cyBusAuthUserAddDto.getDeptName());
                    dbAuthUserDto.setIp(cyBusAuthUserAddDto.getIp());
                    dbAuthUserDto.setCreatedTime(newDate);
                    dbAuthUserDto.setAuthCode(authUserD.getAuthCode());
                    dbAuthUserDto.setAuthName(authUserD.getAuthName());
                    dbAuthUserDtoList.add(dbAuthUserDto);

                    SyncAuthUserDto syncAuthUserDto = new SyncAuthUserDto();
                    syncAuthUserDto.setBusinessIds(businessId);
                    syncAuthUserDto.setPhone(cyBusAuthUserAddDto.getPhone());
                    syncAuthUserDto.setUserName(cyBusAuthUserAddDto.getUserName());
                    syncAuthUserDto.setAuthPhone(cyBusAuthUserAddDto.getAuthPhone());
                    syncAuthUserDto.setAuthUserName(cyBusAuthUserAddDto.getAuthUserName());
                    syncAuthUserDto.setIp(cyBusAuthUserAddDto.getIp());
                    syncAuthUserDto.setSalt(business.getSalt());
                    syncAuthUserDto.setAuthUrl(business.getAuthUrl());
                    syncAuthUserDto.setSystemCode(business.getSystemCode());
                    syncAuthUserDto.setAuthCode(authUserD.getAuthCode());


                    authUserDTO.setDbAuthUserDtoList(dbAuthUserDtoList);
                    authUserDTO.setSyncAuthUserDto(syncAuthUserDto);
                    busMap.put(buid, authUserDTO);
                } else {

                    List<DbAuthUserDto> dbAuthUserDtoList = authUserDTO.getDbAuthUserDtoList();
                    SyncAuthUserDto syncAuthUserDto = authUserDTO.getSyncAuthUserDto();
                    String businessIds = syncAuthUserDto.getBusinessIds();
                    syncAuthUserDto.setBusinessIds(businessIds + "," + businessId);

                    DbAuthUserDto dbAuthUserDto = new DbAuthUserDto();
                    dbAuthUserDto.setBusinessId(businessId);
                    dbAuthUserDto.setBusinessName(business.getName());
                    dbAuthUserDto.setParentBusinessId(businessP.getBusinessId());
                    dbAuthUserDto.setParentBusinessName(businessP.getName());
                    dbAuthUserDto.setPhone(cyBusAuthUserAddDto.getPhone());
                    dbAuthUserDto.setUserName(cyBusAuthUserAddDto.getUserName());
                    dbAuthUserDto.setAuthPhone(cyBusAuthUserAddDto.getAuthPhone());
                    dbAuthUserDto.setAuthUserName(cyBusAuthUserAddDto.getAuthUserName());
                    dbAuthUserDto.setAreaCode(cyBusAuthUserAddDto.getAreaCode());
                    dbAuthUserDto.setAreaName(cyBusAuthUserAddDto.getAreaName());
                    dbAuthUserDto.setOrgId(cyBusAuthUserAddDto.getOrgId());
                    dbAuthUserDto.setOrgName(cyBusAuthUserAddDto.getOrgName());
                    dbAuthUserDto.setDeptId(cyBusAuthUserAddDto.getDeptId());
                    dbAuthUserDto.setDeptName(cyBusAuthUserAddDto.getDeptName());
                    dbAuthUserDto.setIp(cyBusAuthUserAddDto.getIp());
                    dbAuthUserDto.setCreatedTime(newDate);
                    dbAuthUserDto.setAuthCode(authUserD.getAuthCode());
                    dbAuthUserDto.setAuthName(authUserD.getAuthName());
                    dbAuthUserDtoList.add(dbAuthUserDto);

                    String authCode = syncAuthUserDto.getAuthCode();
                    if (StrUtil.isEmpty(authCode)) {
                        syncAuthUserDto.setAuthCode(authUserD.getAuthCode());
                    } else {
                        syncAuthUserDto.setAuthCode(authCode + "," + authUserD.getAuthCode());
                    }

                }
            }

            log.info("cydwsq-busMap:{}",JSONUtil.toJsonStr(busMap));

            Set<String> setData = busMap.keySet();

//            ----------------------
            for (String businessId : setData) {
                log.info("cydwsq-businessId :{} ", businessId);

                AuthUserDTO authUserDTO = busMap.get(businessId);
                List<DbAuthUserDto> dbAuthUserDtoList = authUserDTO.getDbAuthUserDtoList();
                SyncAuthUserDto syncAuthUserDto = authUserDTO.getSyncAuthUserDto();

                String authCode = syncAuthUserDto.getAuthCode();
                String businessIds = syncAuthUserDto.getBusinessIds();
                boolean tb = false;


                //查询code是否存在
                String[] authCodeStr = authCode.split(",");
                String[] businessIdsStr = businessIds.split(",");
                for (int i = 0; i < authCodeStr.length; i++) {
                    String ac = authCodeStr[i];
                    LambdaQueryWrapper qw = new LambdaQueryWrapper<CsBusinessUserAuth>()
                            .eq(CsBusinessUserAuth::getPhone, cyBusAuthUserAddDto.getPhone())
                            .eq(CsBusinessUserAuth::getBusinessId, businessIdsStr[i])
                            .eq(CsBusinessUserAuth::getAuthCode, ac);
                    int count = csBusinessUserAuthService.count(qw);
                    if (count <= 0) {
                        tb = true;
                    }
                }

                //特殊处理
                if (authCode.contains(",")) {
                    LambdaQueryWrapper qw = new LambdaQueryWrapper<CsBusinessUserAuth>()
                            .eq(CsBusinessUserAuth::getPhone, cyBusAuthUserAddDto.getPhone())
                            .like(CsBusinessUserAuth::getBusinessId, businessId);
                    int count = csBusinessUserAuthService.count(qw);
                    if (authCodeStr.length < count) {
                        tb = true;
                    }
                }

                if (tb) {
                    try {

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("phone", syncAuthUserDto.getPhone());
                        jsonObject.put("userName", syncAuthUserDto.getUserName());
                        jsonObject.put("authPhone", syncAuthUserDto.getAuthPhone());
                        jsonObject.put("authUserName", syncAuthUserDto.getAuthUserName());
                        jsonObject.put("ip", syncAuthUserDto.getIp());
                        jsonObject.put("authCode", syncAuthUserDto.getAuthCode());
                        String sign = JsonDataSecurity.encryptJsonData(jsonObject, syncAuthUserDto.getSalt());
                        jsonObject.put("sign", sign);
                        log.info("cydwsq-jsonObject:{} :{}", businessIds, jsonObject.toString());

                        if (null != syncAuthUserDto.getSystemCode() ){
                            ApiRes apiRes = addHierarchyConfirm(syncAuthUserDto.getPhone(), syncAuthUserDto.getSystemCode());
                            if (ApiCodeEnum.SUCCESS.getCode() != apiRes.getCode()) {
                                log.info("cydwsq-erro-id:{}", businessId);
                            }
                        }else {
                            log.info("businessId-isSystemCode-null:{}",businessId);
                        }

                        int codeC = syncUserAuthEdit(jsonObject, syncAuthUserDto.getAuthUrl());
                        if (ApiCodeEnum.SUCCESS.getCode() != codeC) {
                            log.info("cydwsq-erro-id:{}", businessId);
                        } else {

                            if (authCode.contains(",")) {
                                for (int i = 1; i < 5; i++) {
                                    csBusinessUserAuthService.remove(new LambdaQueryWrapper<CsBusinessUserAuth>()
                                            .eq(CsBusinessUserAuth::getPhone, cyBusAuthUserAddDto.getPhone())
                                            .eq(CsBusinessUserAuth::getBusinessId, businessId + "=" + i));
//                                    csBusinessUserCodeService.remove(new LambdaQueryWrapper<CsBusinessUserCode>()
//                                            .eq(CsBusinessUserCode::getBusinessId, businessId + "=" + i)
//                                            .eq(CsBusinessUserCode::getPhone, bean.getPhone()));
                                    csBusinessUserService.remove(new LambdaQueryWrapper<CsBusinessUser>()
                                            .eq(CsBusinessUser::getPhone, cyBusAuthUserAddDto.getPhone())
                                            .eq(CsBusinessUser::getBusinessId, businessId + "=" + i));
                                }
                            }

                            for (DbAuthUserDto dbAuthUserDto : dbAuthUserDtoList) {

                                CsBusinessUserAuth businessUserAuth = new CsBusinessUserAuth();
                                BeanUtils.copyProperties(dbAuthUserDto, businessUserAuth);
                                businessUserAuth.setBusinessId(dbAuthUserDto.getBusinessId());
                                businessUserAuth.setBusinessName(dbAuthUserDto.getBusinessName());
                                businessUserAuth.setParentBusinessId(dbAuthUserDto.getParentBusinessId());
                                businessUserAuth.setParentBusinessName(dbAuthUserDto.getParentBusinessName());

//                                CsBusinessUserCode userCode = new CsBusinessUserCode();
//                                BeanUtils.copyProperties(dbAuthUserDto, userCode);

                                CsBusinessUser csBusinessUser = new CsBusinessUser();
                                csBusinessUser.setBusinessId(dbAuthUserDto.getBusinessId());
                                csBusinessUser.setBusinessName(dbAuthUserDto.getBusinessName());
                                csBusinessUser.setParentBusinessId(dbAuthUserDto.getParentBusinessId());
                                csBusinessUser.setParentBusinessName(dbAuthUserDto.getParentBusinessName());
                                csBusinessUser.setCreatedTime(newDate);
                                csBusinessUser.setPhone(cyBusAuthUserAddDto.getPhone());
                                csBusinessUser.setCreatedBy(cyBusAuthUserAddDto.getAuthPhone());


                                csBusinessUserAuthService.remove(new LambdaQueryWrapper<CsBusinessUserAuth>()
                                        .eq(CsBusinessUserAuth::getPhone, cyBusAuthUserAddDto.getPhone())
                                        .eq(CsBusinessUserAuth::getBusinessId, dbAuthUserDto.getBusinessId()));
                                csBusinessUserService.remove(new LambdaQueryWrapper<CsBusinessUser>()
                                        .eq(CsBusinessUser::getPhone, cyBusAuthUserAddDto.getPhone())
                                        .eq(CsBusinessUser::getBusinessId, dbAuthUserDto.getBusinessId()));
//                                csBusinessUserCodeService.remove(new LambdaQueryWrapper<CsBusinessUserCode>()
//                                        .eq(CsBusinessUserCode::getBusinessId, dbAuthUserDto.getBusinessId())
//                                        .eq(CsBusinessUserCode::getPhone, bean.getPhone()));
                                csBusinessUserAuthService.save(businessUserAuth);
                                csBusinessUserService.save(csBusinessUser);
//                                csBusinessUserCodeService.save(userCode);
                            }
                        }

                    } catch (Exception e) {
                        log.info("addAuthUser-Exception-businessId:{} e:{}", businessId, e);
                    }
                } else {
                    log.info("not-b-businessId:{}", businessId);
                }

            }
//            ----------------------


        }catch( Exception e){
            log.info("cydwsq-Exception-e:{}", e);
        }
    }

    public ApiRes addHierarchyConfirm(String phone,String systemCode) {
        String url = "http://10.8.12.118:8091/pfc/cfg/system/v1/addHierarchyConfirm";

        Map<String, String > heads = new HashMap<>();
        // 使用json发送请求，下面的是必须的
        heads.put("Content-Type", "application/json;charset=UTF-8");
        JSONObject json = new JSONObject();
        json.put("phone", phone);
        json.put("systemCode", systemCode);
        /**
         ** headerMap是添加的请求头，
         body是传入的参数，这里选择json，后端使用@RequestBody接收
         */
        log.info("addHierarchyConfirm-url:{} ",url);
        HttpResponse response = HttpRequest.post(url)
                .headerMap(heads, false)
                .body(json.toString())
                .timeout(5 * 60 * 1000)
                .execute();
        String result = response.body();
        log.info("addHierarchyConfirm-result:{} json:{}",result,json.toString());
        ApiRes apiRes = JSONUtil.toBean(result, ApiRes.class);
        return apiRes;

    }

}
